import React, { Component } from 'react';
import { getNewsType, getNews } from '../../utils/api';
import './News.css';

export default class News extends Component {
	state = {
		// 新闻类型数组
		types: [],
		// 当前新闻类型id
		currentTypeId: 0,
		// 新闻数组
		newsList: []
	}
	componentDidMount () {
		window.scroll(0, 0);
		this.getNewss();
	}
	// 获取新闻和新闻类型
	async getNewss () {
		let types = await getNewsType();
		if (types.status === 0) {
			this.setState({
				types: types.data,
				currentTypeId: types.data[0].newstypeid
			}, function () {
				this.getNewsneirong(this.state.currentTypeId);
			})
		} else {
			window.alert(types.message);
		}
	}
	async getNewsneirong (typeId) {
		let newsList = await getNews(typeId);
		if (newsList.status === 0) {
			this.setState({
				newsList: newsList.data
			})
		} else {
			window.alert(newsList.message);
		}
	}
	// 切换新闻类型
	changeType (typeId) {
		this.getNewsneirong(typeId);
		this.setState({
			currentTypeId: typeId
		})
	}
	render () {
		let { types, currentTypeId, newsList } = this.state;
		return (
			<div className="news">
				<div className='news_tag'>
					<div className='news_tag_f'>
						<h2>类型</h2>
						<ul>
							{types.map((item) =>
								(<li key={item.newstypeid} onClick={() => { this.changeType(item.newstypeid) }} className={currentTypeId === item.newstypeid ? 'active' : 'red'}>{item.newstype_name}</li>)
							)}
						</ul>
					</div>
				</div>
				<div className="news_c">
					<ul>
						{newsList.map((item) => (
							<li key={item.newsid}>
								<h2>{item.news_title}</h2>
								<div className="time">{item.news_create_time}</div>
								<div className="news_p" dangerouslySetInnerHTML={{ __html: item.news_content }}></div>
							</li>
						))}
					</ul>
				</div>
			</div>
		)
	}
}
